package com.tuling.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

@Controller
public class DownLoadController {

    private final static String utf8 ="utf-8";

    @RequestMapping("/download")
    public void downLoadFile(HttpServletRequest request, HttpServletResponse response) throws Exception {
        File file = new File("C:\\Users\\admin\\nginx原理.mp4");
        response.setCharacterEncoding(utf8);
        InputStream is = null;
        OutputStream os = null;
        try{
            //分片下载   http  Range bytes=100-1000   bytes=100-
            long fSize = file.length();
            String fileName = URLEncoder.encode(file.getName(),utf8);
            // 响应前端是下载类型
            response.setContentType("application/x-download");
            // 告诉前端打开另存为对话框
            response.addHeader("Content-Disposition","attachment;filename=" + fileName);
            // 是否支持分片下载
            response.setHeader("Accept-Range","bytes");
            response.setHeader("fSize",String.valueOf(fSize));
            response.setHeader("fName",fileName);

            // pos：开始读取位置  last：读取结束位置   sum：已经读取完的字节数
            long pos = 0,last = fSize-1,sum = 0;
            if( null != request.getHeader("Range") ){
                // 告诉http客户端是一个断点下载，不能响应200,200代表请求结束； 206代表是分片下载
                response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);

                String numRange = request.getHeader("Range").replaceAll("bytes=","");
                String[] strRange = numRange.split("-");
                if(strRange.length == 2){
                    pos = Long.parseLong(strRange[0].trim());
                    last = Long.parseLong(strRange[1].trim());
                    if(last > fSize-1){
                        last = fSize-1;
                    }
                }else{
                    pos = Long.parseLong(numRange.replaceAll("-","").trim());
                }

            }

            // 开始读取文件
            // 每次读取多少
            long rangeLenght = (last - pos) +1;
            String contentRange = new StringBuffer("bytes ").append(pos).append("-").append(last).append("/").append(fSize).toString();
            response.setHeader("Content-Range",contentRange);
            response.setHeader("Content-Lenght",String.valueOf(rangeLenght));

            os = new BufferedOutputStream(response.getOutputStream());
            is = new BufferedInputStream(new FileInputStream(file));
            is.skip(pos);
            byte[] buffer = new byte[1024];
            int lenght = 0;
            while(sum < rangeLenght){
                lenght = is.read( buffer,0,(rangeLenght-sum) <= buffer.length ?  (int)(rangeLenght-sum) :  buffer.length );
                sum = sum+ lenght;
                os.write(buffer,0,lenght);
            }
            System.out.println("下载完成");

        }finally {
            if(is != null){
                is.close();
            }
            if(os != null){
                os.close();
            }
        }

    }

}
